package com.leafsaas.snowflake;

import java.util.Date;

/**
 *
 * Twitter 雪花算法 Java 实现
 * 64 bit = 0(1) + timestamp(41) + datacenterId(5) + workerId(5) + sequence(12)
 * 支持 2^12 = 4096 /ms /node
 *
 * @author houxifeng
 * @date 2025/11/5
 */
public class SnowflakeIdWorker {

    // ==================  Bit 位  ==================
    /**
     * 开始时间戳(2023-01-01) - 69 年寿命
     */
    private final long twepoch = 1672531200000L;

    /**
     * 机器 ID 所占位数
     */
    private final long workerIdBits = 5L;

    /**
     * 数据中心 ID 所占位数
     */
    private final long datacenterIdBits = 5L;

    /**
     * 序列 所占位数
     */
    private final long sequenceBits = 12L;

    /**
     * 最大支持机器 ID 31
     */
    private final long maxWorkerId = ~(-1L << workerIdBits);

    /**
     * 最大支持数据中心 ID 31
     */
    private final long maxDatacenterId = ~(-1L << datacenterIdBits);

    /**
     * 各段移位
     */
    private final long workerIdShift = sequenceBits;
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /**
     * 序列掩码 4095
     */
    private final long sequenceMask = ~(-1L << sequenceBits);

    // ==================  状态  ==================
    private final long workerId;
    private final long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    // ==================  构造  ==================

    public SnowflakeIdWorker(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException("worker Id 非法");
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException("datacenter Id 非法");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    // ==================  生成 ID  ==================
    public synchronized long nextId() {
        long timestamp = timeGen();
        // 时钟回波保护
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            // 容忍 5ms 小回拨
            if (offset <= 5) {
                try {
                    Thread.sleep(offset + 1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                timestamp = timeGen();
                if (timestamp < lastTimestamp) {
                    throw new RuntimeException("时钟回拨超过 5 ms，拒绝生成 ID");
                }
            } else {
                throw new RuntimeException("时钟回拨大于 5 ms，拒绝生成 ID");
            }
        }

        // 同一毫秒内序列自增
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNexMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift)
                | sequence;
    }


    // ==================  工具  ==================

    /**
     * 获取当前时间戳
     *
     * @return 返回当前时间（以毫秒为单位）
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    protected long tilNexMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    // ==================  测试  ==================
    public static void main(String[] args) {
        SnowflakeIdWorker worker = new SnowflakeIdWorker(1, 1);
        for (int i = 0; i < 10; i++) {
            long id = worker.nextId();
            System.out.println(id + "->" + new Date(SnowflakeIdWorker.parseTimestamp(id)).toString());
        }
    }

    /**
     * 逆向解析：从 ID 提取时间戳
     */
    public static long parseTimestamp(long id) {
        return (id >> 22) + 1672531200000L;
    }


}
